package com.mgq.juc.design.order.v2;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author MaGuangQi
 * 使用reentrantLock实现
 * @date 2021-12-17 11:23
 **/
@Slf4j
public class OrderPrintV2 {
    private static ReentrantLock lock = new ReentrantLock();
    private static boolean t2Run = false;
    private static Condition condition=lock.newCondition();
    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            lock.lock();
            try {
                log.debug("我负责打印1");
                t2Run = true;
                condition.signal();
            }finally {
                lock.unlock();
            }

        }, "t1");

        Thread t2 = new Thread(() -> {
            lock.lock();
            //
            while (!t2Run) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                log.debug("我负责打印2");
            }finally {
                lock.unlock();
            }


        }, "t2");

        t2.start();
        t1.start();
    }
}
